using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
using JlPay.Sdk.Models;
using JlPay.Sdk.Services;
using System;

namespace JlPay.Sdk.Models.Ledger.Merchconf
{
    /// <summary>
    /// 商户分账发行查询响应
    /// </summary>
    public class MerchIssueQueryResponse : StandardResponse, IComplexFieldHandler
    {
        /// <summary>
        /// 机构代码
        /// </summary>
        [JsonPropertyName("org_code")]
        public string? OrgCode { get; set; }

        /// <summary>
        /// 商户号
        /// </summary>
        [JsonPropertyName("mch_id")]
        public string? MchId { get; set; }

        /// <summary>
        /// 商户名称
        /// </summary>
        [JsonPropertyName("mch_name")]
        public string? MchName { get; set; }

        /// <summary>
        /// 账本模块
        /// </summary>
        [JsonPropertyName("ledger_module")]
        public string? LedgerModule { get; set; }

        /// <summary>
        /// 最大分账比例
        /// </summary>
        [JsonPropertyName("max_split_rate")]
        public string? MaxSplitRate { get; set; }

        /// <summary>
        /// 来源ID列表
        /// </summary>
        [JsonPropertyName("source_ids")]
        public string? SourceIds { get; set; }

        /// <summary>
        /// 费率
        /// </summary>
        [JsonPropertyName("fee_rate")]
        public string? FeeRate { get; set; }

        /// <summary>
        /// 平台贴回
        /// </summary>
        [JsonPropertyName("pbthf")]
        public string? Pbthf { get; set; }

        /// <summary>
        /// 最低金额
        /// </summary>
        [JsonPropertyName("low_amt")]
        public string? LowAmt { get; set; }

        /// <summary>
        /// 最高金额
        /// </summary>
        [JsonPropertyName("up_amt")]
        public string? UpAmt { get; set; }

        /// <summary>
        /// 通知URL
        /// </summary>
        [JsonPropertyName("notify_url")]
        public string? NotifyUrl { get; set; }

        /// <summary>
        /// 开通状态
        /// </summary>
        [JsonPropertyName("status")]
        public string? Status { get; set; }

        /// <summary>
        /// 绑定列表
        /// </summary>
        [JsonPropertyName("bind_list")]
        public List<Bind>? Binds { get; set; }

        /// <summary>
        /// 处理复杂字段
        /// </summary>
        /// <param name="fieldName">字段名</param>
        /// <param name="fieldValue">字段值</param>
        public void HandleComplexField(string fieldName, object fieldValue)
        {
            if (fieldName == "bind_list")
            {
                Console.WriteLine($"处理bind_list字段，类型: {fieldValue?.GetType().Name}, 值: {fieldValue}");
                
                if (fieldValue is JsonElement jsonElement)
                {
                    if (jsonElement.ValueKind == JsonValueKind.Array)
                    {
                        Binds = new List<Bind>();
                        foreach (var item in jsonElement.EnumerateArray())
                        {
                            if (item.ValueKind == JsonValueKind.Object)
                            {
                                var bind = JsonSerializer.Deserialize<Bind>(item.GetRawText(), new JsonSerializerOptions
                                {
                                    PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower
                                });
                                if (bind != null)
                                {
                                    Binds.Add(bind);
                                }
                            }
                        }
                        Console.WriteLine($"解析到 {Binds.Count} 个绑定");
                    }
                }
                else if (fieldValue is System.Collections.IEnumerable enumerable)
                {
                    Binds = new List<Bind>();
                    foreach (var item in enumerable)
                    {
                        if (item is Dictionary<string, object> dict)
                        {
                            var bind = new Bind();
                            if (dict.TryGetValue("rev_mch_id", out var revMchId))
                                bind.RevMchId = revMchId?.ToString();
                            if (dict.TryGetValue("rev_mch_name", out var revMchName))
                                bind.RevMchName = revMchName?.ToString();
                            if (dict.TryGetValue("notify_url", out var notifyUrl))
                                bind.NotifyUrl = notifyUrl?.ToString();
                            if (dict.TryGetValue("source_ids", out var sourceIds))
                                bind.SourceIds = sourceIds?.ToString();
                            Binds.Add(bind);
                        }
                    }
                    Console.WriteLine($"从IEnumerable解析到 {Binds.Count} 个绑定");
                }
                else if (fieldValue is string jsonString)
                {
                    try
                    {
                        var binds = JsonSerializer.Deserialize<List<Bind>>(jsonString, new JsonSerializerOptions
                        {
                            PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower
                        });
                        Binds = binds;
                        Console.WriteLine($"从JSON字符串解析到 {Binds?.Count ?? 0} 个绑定");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"解析JSON字符串失败: {ex.Message}");
                    }
                }
            }
        }
    }
} 